/**
 * @file       godemool/iprinter.cc
 * @brief      printer high level functions.
 * @author     ben "boin" bonoeil
 * @date       2015-02
 */

/* Copyright (c) 2007-2015, ben "boin" bonoeil

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions
   are met:
   * Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
   * Redistributions in binary form must reproduce the above
   copyright notice, this list of conditions and the following
   disclaimer in the documentation and/or other materials provided
   with the distribution.
   * Neither the name of the ben "boin" bonoeil nor the names of its
   contributors may be used to endorse or promote products derived
   from this software without specific prior written permission.

   NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE
   GRANTED BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY
   ben "boin" bonoeil ''AS IS'' AND ANY EXPRESS OR IMPLIED
   WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
   OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   DISCLAIMED. IN NO EVENT SHALL ben "boin" bonoeil BE LIABLE FOR ANY
   DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
   DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
   GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
   INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
   WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include "godemool/iprinter.h"
#include "godemool/error.h"
#include <cstdio>

using namespace boin;

/* Important: Using %a for floating point types should ensure no precision is lost. */
const char * IPrinter::Fmt(bool b)     { return b ? "1" : "0"; }
const char * IPrinter::Fmt(int32_t i)  { sprintf(tmp,"%i",i); return tmp; }
const char * IPrinter::Fmt(uint32_t u) { sprintf(tmp,"%u",u); return tmp; }
const char * IPrinter::Fmt(int64_t i)  { return Fmt(uint64_t(i)); }
const char * IPrinter::Fmt(uint64_t u) {
  sprintf(tmp,"0x%016llx", u); return tmp;
}
const char * IPrinter::Fmt(float f)    { return Fmt(double(f)); }
const char * IPrinter::Fmt(double d)   { sprintf(tmp,"%a", d); return tmp; }

template<typename T>
static bool Is(const Hl2Demo::Chunk * chk, const CodecType & obj)
{
  return typeid(obj) == typeid(T);
}

/* "Raw-Data" is raw ... data */
void IPrinter::Print(const RawData & raw)
{
  BegElt("rawdata"); {
    Attr("size",raw.Size());
    Data(raw);
  } EndElt("rawdata");
}

/* "Custom-Data" is custom ... data */
void IPrinter::Print(const CustomData & custom)
{
  BegElt("customdata"); {
    Attr("size",custom.Size());
    Data(custom);
  } EndElt("customdata");
}

/* "User-Commands" are decoded for the most part (need a bit more testing)
 * but it does not have very interesting information ... data
 * Set IPrinter::detail_usrcmd to dump details.
 */
void IPrinter::Print(const UserCommand & cmd)
{
  BegElt("usrcmd"); {
    Attr("size",cmd.size);
    Data(cmd);
    if (detail_usrcmd && cmd.has.any) {
      BegElt("detail"); {
        if (cmd.has.id) Attr("id", cmd.id);
        if (cmd.has.tick) Attr("tick", cmd.tick);
        static char vname[3][8] = { "dir_x", "aim_x", "mov_x" };
        for (int i=0, m=1; i<3; ++i) {
          for (int j=0; j<3; ++j, m<<=1) {
            if (cmd.has.vect & m) {
              vname[i][4] = 'x'+j;
              Attr(vname[i],(&cmd.vec[i].x)[j]);
            }
          }
        }
        if (cmd.has.buttons) Attr("buttons",cmd.buttons);
        if (cmd.has.impulse) Attr("impulse",cmd.impulse);
        if (cmd.has.weapon) Attr("weapon",cmd.weapon);
        if (cmd.has.subwpn) Attr("subwpn",cmd.subwpn);
        if (cmd.has.mousedx) Attr("mousex",cmd.mousedx);
        if (cmd.has.mousedy) Attr("mousex",cmd.mousedy);
      } EndElt("detail");
    }
  } EndElt("usrcmd");
}

void IPrinter::Print(const ConCommand & cmd)
{
  BegElt("concmd"); { Str(cmd.c_str()); } EndElt("concmd");
}

void IPrinter::Print(const DataTables & dtables)
{
  BegElt("datatables"); {
    BegElt("sendtables"); {
      int size = dtables.sendtables.size();
      Attr("count",size);
      for (int i=0; i<size; ++i) {
        const SendTable & st = dtables.sendtables[i];
        BegElt("sendtable"); {
          Attr("dtid",i);
          Attr("type",st.type);
          Attr("name",st.msg.GetTypeName().c_str());
          Print(&st.msg);
        }; EndElt("sendtable");
      }
    } EndElt("sendtables");
    BegElt("srvclasses"); {
      int size = dtables.srvclasses.size();
      Attr("count", size);
      for (int i=0; i<size; ++i) {
        const ServerClass & sc = dtables.srvclasses[i];
        BegElt("srvclass"); {
          assert(sc.idx == i);
          Attr("dtid",sc.dtidx);
          Attr("dtname",sc.dtname.c_str());
          Attr("name",sc.name.c_str());
        }; EndElt("srvclass");
      }
    }; EndElt("srvclasses");
  } EndElt("datatables");
}

void IPrinter::Print(const std::vector<StringTable::String> & strings)
{
  for (unsigned int j = 0; j < strings.size(); ++j) {
    BegElt("string"); {
      BegElt("name"); { Str(strings[j].name.c_str()); } EndElt("name");
      if (strings[j].data.Size() > 0) {
        BegElt("data"); {
          Attr("size",strings[j].data.Size());
          Data(strings[j].data);
        } EndElt("data");
      }
    } EndElt("string");
  }
}

void IPrinter::Print(const StringTables & tables)
{
  BegElt("stringtables");
  Attr("num", tables.size());
  for (unsigned int i = 0; i < tables.size(); ++i) {
    const StringTable & st = tables[i];
    BegElt("stringtable"); {
      Print(st.strdata);
      if (st.usrdata.size()) {
        BegElt("userdata"); {
          Print(st.usrdata);
        } EndElt("userdata");
      }
    }
    EndElt("stringtable");
  }
  EndElt("stringtables");
}

void IPrinter::Print(const google::protobuf::Message * msg, int idx)
{
  // Fill a vector with the used fields.
  const google::protobuf::Reflection* reflection = msg->GetReflection();
  std::vector<const google::protobuf::FieldDescriptor*> fields;
  reflection->ListFields(*msg, &fields);

  BegElt("msg");
  if (idx != -1) Attr("idx",idx);
  //Attr("type",);
  Attr("name",msg->GetTypeName().c_str());

  // $$$ Special case for event just to help readabilty
  if (typeid(*msg) == typeid(CSVCMsg_GameEvent)) {
    const CSVCMsg_GameEvent * ge = (CSVCMsg_GameEvent*) msg;
    if (!ge->has_event_name())  {
      if (ge->has_eventid()) {
        int32_t eid = ge->eventid();
        const Decoder::EventDesc * desc = GetEvent(eid);
        if (desc)
          Attr("eventname",desc->name);
      }
    }
  }

  // Must be already indented (easier to print index).
  for (int i = 0; i < (int)fields.size(); i++) {
    const google::protobuf::FieldDescriptor *fd = fields[i];
    const int fcnt = fd->is_repeated() ? reflection->FieldSize(*msg,fd) : 0;

    BegElt(fd->name().c_str());
    //Attr("idx",fd->index());
    AttrIfTrue("opt",fd->is_optional());
    AttrIfTrue("req",fd->is_required());
    Attr("type",fd->type_name());
    if (fcnt) Attr("count",fcnt);

#define GTYPE(T) google::protobuf::FieldDescriptor::T
    switch (fd->type()) {

    case GTYPE(TYPE_DOUBLE):   // double, exactly eight bytes on the wire.
      if (!fcnt)
        Str(reflection->GetDouble(*msg,fd));
      else for (int j=0; j<fcnt; ++j) {
	  BegElt("val");
	  Attr("idx",j);
	  Str(reflection->GetRepeatedDouble(*msg,fd,j));
	  EndElt("val");
	}
      break;

    case GTYPE(TYPE_FLOAT):    // float, exactly four bytes on the wire.
      if (!fcnt)
        Str(reflection->GetFloat(*msg,fd));
      else for (int j=0; j<fcnt; ++j) {
	  BegElt("val");
	  Attr("idx",j);
	  Str(reflection->GetRepeatedFloat(*msg,fd,j));
	  EndElt("val");
	}
      break;

    case GTYPE(TYPE_INT64):    // int64, varint on the wire.
    case GTYPE(TYPE_SFIXED64): // int64, exactly eight bytes on the wire
    case GTYPE(TYPE_SINT64):   // int64, ZigZag-encoded varint on the wire
      if (!fcnt)
        Str(reflection->GetInt64(*msg,fd));
      else for (int j=0; j<fcnt; ++j) {
	  BegElt("val");
	  Attr("idx",j);
	  Str(reflection->GetRepeatedInt64(*msg,fd,j));
	  EndElt("val");
	}
    break;

    case GTYPE(TYPE_UINT64):   // uint64, varint on the wire.
    case GTYPE(TYPE_FIXED64):  // uint64, exactly eight bytes on the wire.
      if (!fcnt)
        Str(reflection->GetUInt64(*msg,fd));
      else for (int j=0; j<fcnt; ++j) {
	  BegElt("val");
	  Attr("idx",j);
	  Str(reflection->GetRepeatedUInt64(*msg,fd,j));
	  EndElt("val");
	}
    break;

    case GTYPE(TYPE_SFIXED32): // int32, exactly four bytes on the wire
    case GTYPE(TYPE_SINT32):   // int32, ZigZag-encoded varint on the wire
    case GTYPE(TYPE_INT32):    // int32, varint on the wire.
      if (!fcnt)
        Str(int32_t(reflection->GetInt32(*msg,fd)));
      else for (int j=0; j<fcnt; ++j) {
	  BegElt("val");
	  Attr("idx",j);
	  Str(int32_t(reflection->GetRepeatedInt32(*msg,fd,j)));
	  EndElt("val");
	}
    break; 

    case GTYPE(TYPE_UINT32):   // uint32, varint on the wire
    case GTYPE(TYPE_FIXED32):  // uint32, exactly four bytes on the wire.
      if (!fcnt)
        Str(uint32_t(reflection->GetUInt32(*msg,fd)));
      else for (int j=0; j<fcnt; ++j) {
	  BegElt("val");
	  Attr("idx",j);
	  Str(uint32_t(reflection->GetRepeatedUInt32(*msg,fd,j)));
	  EndElt("val");
	}
    break;

    case GTYPE(TYPE_BOOL):     // bool, varint on the wire.
      if (!fcnt)
        Str(bool(reflection->GetBool(*msg,fd)));
      else for (int j=0; j<fcnt; ++j) {
	  BegElt("val");
	  Attr("idx",j);
	  Str(bool(reflection->GetRepeatedBool(*msg,fd,j)));
	  EndElt("val");
	}
      break;

    case GTYPE(TYPE_STRING):   // UTF-8 text.
      if (!fcnt) {
        std::string tmp;
        Str(reflection->GetStringReference(*msg,fd,&tmp).c_str());
      } else for (int j=0; j<fcnt; ++j) {
	  std::string tmp;
	  BegElt("val");
	  Attr("idx",j);
	  Str(reflection->GetRepeatedStringReference(*msg,fd,j,&tmp).c_str());
	  EndElt("val");
	}
      break;

    case GTYPE(TYPE_GROUP):    // Tag-delimited message.  Deprecated.
      throw Error(Error::input, "type group");
      if (!fcnt)
        assert(!"TODO");
      else
        assert(!"TODO");
      break;

    case GTYPE(TYPE_MESSAGE):  // Length-delimited message.
      if (!fcnt)
        Print(&reflection->GetMessage(*msg,fd));
      else for (int j = 0; j < fcnt ; ++j)
	     Print(&reflection->GetRepeatedMessage(*msg,fd,j)/*,j*/);
      break;

    case GTYPE(TYPE_BYTES):    // Arbitrary byte array.
      BegElt("val"); {
        std::string tmp;
        WalkStringRef walk = WalkStringRef(reflection->GetStringReference(*msg,fd,&tmp));
        Attr("size",walk.Size());
        Data(walk);
      } EndElt("val");
      break;

    case GTYPE(TYPE_ENUM):     // Enum, varint on the wire
      if (!fcnt) {
        const google::protobuf::EnumValueDescriptor * e = reflection->GetEnum(*msg,fd);
        Attr("symbolic", e->name().c_str());
        Str(uint32_t(e->number()));
      } else for (int j = 0; j < fcnt ; ++j) {
	  const google::protobuf::EnumValueDescriptor * e = reflection->GetRepeatedEnum(*msg,fd,j);
	  BegElt("val"); Attr("idx",j); Attr("symbolic", e->name().c_str());
	  Attr("idx",j);
	  EndElt("val");
	}
      break;

    default:
      throw Error(Error::input, std::string("field type ") += fd->type());
    }
    EndElt(fd->name().c_str());
  }
  EndElt("msg");
}

void IPrinter::Print(const Messages & messages)
{
  BegElt("messages");
  Attr("count",messages.size());
  Attr("inp",messages.seqInp);
  Attr("out",messages.seqOut);
  for (unsigned int i=0; i < messages.size(); ++i)
    Print(messages[i].msg/*,i*/);
  EndElt("messages");
}

void IPrinter::Print(const Hl2Demo::Chunk * chk, const CodecType * obj)
{
  assert(chk);
  assert(obj);

  BegElt("chunk"); {
    Attr("type",chk->type);
    Attr("name",chk->TypeName());
    Attr("idx",chk->idx);
    Attr("tick",chk->tick);
    Attr("slot",chk->slot);
  }

  if (Is<Messages>(chk,*obj)) {
    Print(*(Messages *)obj);
  } else if (Is<UserCommand>(chk,*obj)) {
    Print(*(UserCommand*)obj);
  } else if (Is<RawData>(chk,*obj)) {
    Print(*(RawData*)obj);
  } else if (Is<CustomData>(chk,*obj)) {
    Print(*(CustomData*)obj);
  } else if (Is<ConCommand>(chk,*obj)) {
    Print(*(ConCommand *)obj);
  } else if (Is<StringTables>(chk,*obj)) {
    Print(*(StringTables *)obj);
  } else if (Is<DataTables>(chk,*obj)) {
    Print(*(DataTables*)obj);
  } else if (Is<CodecType>(chk,*obj)) {
    assert(!"No it's not");
  } else {
    assert(! "unexpected object");
  }

  EndElt("chunk");
}

void IPrinter::Print(const Hl2Demo::Header & hd)
{
  BegElt("header"); {
    BegElt("version"); {
      Attr("demo",hd.dem_ver);
      Attr("protocol",hd.net_ver);
    } EndElt("version");
    BegElt("names"); {
      BegElt("server"); Str(hd.sv_name); EndElt("server");
      BegElt("client"); Str(hd.tv_name); EndElt("client");
      BegElt("map"); Str(hd.mp_name); EndElt("map");
      BegElt("game"); Str(hd.gm_name); EndElt("game");
    } EndElt("names");
    BegElt("duration"); {
      Attr("seconds",hd.pb_time);
      Attr("ticks",hd.pb_tick);
      Attr("frames",hd.pb_fram);
    } EndElt("duration");
    BegElt("signon"); Attr("len",hd.sig_len); EndElt("signon");
  } EndElt("header");
}
